import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/pages/event/GetCardEven.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/LoadingUtil.dart';
import 'package:flutter_yres/tool/constant.dart';
import '../../tool/md5_sign.dart';

class BindZfbPage extends StatefulWidget {
  String type;
  BindZfbPage({Key key, this.type}) : super(key: key);

  @override
  _BindZfbPageState createState() => _BindZfbPageState();
}

class _BindZfbPageState extends State<BindZfbPage> {
  
 
  String token = "";
  String codeString = "获取验证码";
  int codeStatus = 1;
   Timer _countdownTimer;
  int _countdownNum = 59;
  String code = "", account = "", name = "", truename = "";
  String bank_id = '';
  String id = ''; //银行卡ID
  final _userCodeController = TextEditingController(); //验证码
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text(
          '绑定支付宝',
          style: TextStyle(
              color: black,
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
        ),
        elevation: 0.2,
        backgroundColor: white,
        iconTheme: new IconThemeData(color: black_99),
        brightness: Brightness.light,
      ),
      body: new Container(
          width: double.infinity,
          color: white,
          child: new Column(children: <Widget>[
            Container(
                width: double.infinity,
                color: f0Color,
                padding:
                    EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
                child: Text(
                  '已绑定支付宝: $account',
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      color: Colors.black54),
                )),
            // Container(
            //   padding: EdgeInsets.only(
            //       top: ScreenUtil.getInstance().setHeight(DP_15),
            //       left: ScreenUtil.getInstance().setHeight(DP_20),
            //       right: ScreenUtil.getInstance().setHeight(DP_20)),
            //   child: Row(children: <Widget>[
            //     new Expanded(
            //         child: new TextField(
            //       keyboardAppearance: Brightness.light,
            //       keyboardType: TextInputType.numberWithOptions(),
            //       maxLines: 1,
            //       onChanged: (value) {
            //         code = value;
            //       },
            //       style: TextStyle(
            //           fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
            //       cursorColor: mainColor,
            //       decoration: new InputDecoration(
            //           hintText: "短信验证码",
            //           border: InputBorder.none,
            //           hintStyle: TextStyle(
            //               fontSize: ScreenUtil.getInstance()
            //                   .setSp(NORMAL_FONT_SIZE))),
            //     )),
            //     new Container(
            //       width: ScreenUtil.getInstance().setWidth(DP_200 + 5),
            //       height: ScreenUtil.getInstance().setHeight(DP_50),
            //       margin: EdgeInsets.fromLTRB(0, 0, 0, 8),
            //       decoration: new BoxDecoration(
            //           gradient: LinearGradient(
            //               colors: codeStatus == 0
            //                   ? [
            //                       Color.fromARGB(255, 99, 99, 99),
            //                       Color.fromARGB(255, 99, 99, 99)
            //                     ]
            //                   : [mainColor, mainColor]),
            //           borderRadius: BorderRadius.circular(20.0)),
            //       child: new FlatButton(
            //         child: new Padding(
            //           padding: EdgeInsets.all(0.0),
            //           child: new Text(
            //             "$codeString",
            //             style: new TextStyle(
            //                 color: Colors.white,
            //                 fontSize: ScreenUtil.getInstance()
            //                     .setSp(SMALL_FONT_SIZE)),
            //           ),
            //         ),
            //         onPressed: () {
            //           // if (codeStatus == 0) {
            //           //   return;
            //           // }
            //           // if (userController.text.isEmpty) {
            //           //   Fluttertoast.showToast(msg: "请输入手机号");
            //           //   return;
            //           // }
            //           showDialog(
            //               context: context,
            //               barrierDismissible: false,
            //               builder: (_) {
            //                 return new NetLoadingDialog(
            //                   loadingText: "获取中...",
            //                   bgColor: Color.fromARGB(255, 0, 0, 0),
            //                   requestCallBack: null,
            //                   outsideDismiss: false,
            //                 );
            //               });
            //           getPhoneCode();
            //         },
            //       ),
            //     )
            //   ]),
            // ),
            Container(height: 1, color: f0Color),
            Container(
              padding: EdgeInsets.only(
                  top: ScreenUtil.getInstance().setHeight(DP_10),
                  left: ScreenUtil.getInstance().setHeight(DP_20),
                  right: ScreenUtil.getInstance().setHeight(DP_20)),
              child: Row(children: <Widget>[
                new Expanded(
                    child: new TextField(
                  keyboardAppearance: Brightness.light,
                  // keyboardType: TextInputType.numberWithOptions(),
                  maxLines: 1,
                  onChanged: (value) {
                    account = value;
                  },
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                  cursorColor: mainColor,
                  decoration: new InputDecoration(
                      hintText: "支付宝账号",
                      border: InputBorder.none,
                      hintStyle: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                )),
              ]),
            ),
            Container(height: 1, color: f0Color),
            Container(
              padding: EdgeInsets.only(
                  top: ScreenUtil.getInstance().setHeight(DP_10),
                  left: ScreenUtil.getInstance().setHeight(DP_20),
                  right: ScreenUtil.getInstance().setHeight(DP_20)),
              child: Row(children: <Widget>[
                new Expanded(
                    child: new TextField(
                  keyboardAppearance: Brightness.light,
                  // keyboardType: TextInputType.numberWithOptions(),
                  maxLines: 1,
                  onChanged: (value) {
                    name = value;
                  },
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                  cursorColor: mainColor,
                  decoration: new InputDecoration(
                      hintText: "真实姓名(与支付宝对应)",
                      border: InputBorder.none,
                      hintStyle: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                )),
              ]),
            ),
            Container(height: 1, color: f0Color),
            createBtnInputText(_userCodeController,
                hint: '',
                title: '手机验证码',
                obscureText: false,
                type: TextInputType.phone),
            Container(height: 1, color: f0Color),
            new Container(
              width: double.infinity,
              margin: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_50)),
              height: ScreenUtil.getInstance().setWidth(DP_90),
              decoration: new BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(DP_80)),
              padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
              child: new FlatButton(
                child: new Padding(
                  padding: EdgeInsets.all(0.0),
                  child: new Text(
                    "立即绑定",
                    style: new TextStyle(
                        color: Colors.white,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                  ),
                ),
                onPressed: () {
                  // if (code == "") {
                  //   Fluttertoast.showToast(msg: "请填写验证码");
                  //   return;
                  // }
                  if (account == "") {
                    Toast.toast(context, msg: "请填写支付宝账号");
                    return;
                  }
                  if (name == "") {
                    Toast.toast(context, msg: "请填写姓名");
                    return;
                  }
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) {
                        return new NetLoadingDialog(
                          loadingText: "绑定中...",
                          bgColor: Color.fromARGB(255, 0, 0, 0),
                          requestCallBack: null,
                          outsideDismiss: false,
                        );
                      });
                  bind();
                  // _checkSub(context);
                },
              ),
            )
          ])),
    );
  }

// /图标 + 输入框+ 按钮
  Widget createBtnInputText(TextEditingController controller,
      {obscureText: false, String hint, String title, TextInputType type}) {
    return Padding(
        padding: new EdgeInsets.fromLTRB(
            0,
            ScreenUtil.getInstance().setWidth(20),
            ScreenUtil.getInstance().setWidth(20) * 2,
            0),
        child: new Stack(
          alignment: new Alignment(1.0, 1.0),
          //statck
          children: <Widget>[
            new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  // new Padding(
                  //   padding: new EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0),
                  //   child: Text(title),
                  // ),
                  Expanded(
                      child: new Container(
                    // width: kScreenWidth * 0.45,
                    margin: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_20), 0, 0, 0),
                    child: new TextField(
                        // focusNode: _contentFocusNode,
                        controller: controller,
                        keyboardType: type,
                        decoration: new InputDecoration(
                          border: InputBorder.none,
                          hintText: title,
                        ),
                        obscureText: obscureText),
                  )),
                  Container(
                    width: ScreenUtil.getInstance().setWidth(200),
                    child: new MaterialButton(
                      // color: codeStatus == 1 ? Colors.blue : Colors.grey,
                      textColor: codeStatus == 1 ? Colors.blue : Colors.grey,
                      child: new Text(
                        codeString,
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance().setSp(26)),
                      ),
                      onPressed: () {
                        sendNewCode();
                      },
                    ),
                  )
                ]),
            Divider(
              height: 1,
            ),
          ],
        ));
  }

  sendNewCode() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    //  if (account == '') {
    //   Toast.toast(context, msg: '填写绑定手机号');
    //   return;
    // }
    Map map = Map();
    map["token"] = preferences.get("token");
    map['sign_type'] = 'yres.sms';
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + '/app.php?c=Sms&a=sendDrawPwdCode',
        data: getSign(map));
    Map userMap = json.decode(response.data);
    Toast.toast(context, msg: userMap['msg']);
    int code = userMap['code'];
    if (code == 1) {
      print(userMap);
      setState(() {
        codeStatus = 0;
        if (_countdownTimer != null) {
          return;
        }
        codeString = '${_countdownNum--}重新获取';
        _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
          setState(() {
            if (_countdownNum > 0) {
              codeStatus = 0;
              codeString = '${_countdownNum--}重新获取';
            } else {
              codeString = '获取验证码';
              codeStatus = 1;
              _countdownNum = 59;
              _countdownTimer.cancel();
              _countdownTimer = null;
            }
          });
        });
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString('token').then((value) {
      token = value;
      if (widget.type == '1') {//添加
        getBankList();
      } else {//修改
        card();
      }
    });
    truename = '';
    // truename=APPLIC.userInfoMap['user_detail']['alipay_account'];
    setState(() {});
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }

  card() async {
    //先判断银行卡有没有添加过关于支付宝的账号
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetAccountListUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    int code = userMap["code"];
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      List list = userMap['data']['list'];
      setState(() {
        if (list.length == 1) {
          id = userMap['data']['list'][0]['id'];
          account = userMap['data']['list'][0]['account'];
          bank_id = userMap['data']['list'][0]['bank_id'];
        }
      });
    }
  }

  getBankList() async {
    //获取银行
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetBankListUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    int code = userMap["code"];
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      bank_id = userMap['data']['list'][0]['bank_id'];
    }
  }

  bind() async {
    if (_userCodeController.text == '' || name == '' || account == '') {
      Navigator.of(context).pop(1);
      Toast.toast(context, msg: '填写完整信息');
      return;
    }
    if (widget.type == '1') {//第一次添加
      FormData data = new FormData.fromMap({
        'token': token,
        'bank_id': bank_id,
        'account': account,
        'truename': name,
        'code': _userCodeController.text
      });
      Response<String> response =
          await HttpUtil().post(Api.AddCardUrl, data: data);
      Map userMap = json.decode(response.data);
      int result = userMap["code"];
      String msg = userMap["msg"];
      Navigator.of(context).pop(1);
      Toast.toast(context, msg: msg);
      if (result == 1 && mounted) {
        // APPLIC.eventBus.fire(LoginEvent());
        Navigator.of(context).pop();
      }
    } else {
      Map map = new Map();
      map['token'] = token;
      map['id'] = id;
      map['bank_id'] = bank_id;
      map['account'] = account;
      map['truename'] = name;
      map['code'] = _userCodeController.text;
      print(map);
      FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
      Response<String> response =
          await HttpUtil().post(Api.EditCardUrl, data: data);
      Map userMap = json.decode(response.data);
      int result = userMap["code"];
      String msg = userMap["msg"];
       Navigator.of(context).pop(1);
      print(userMap);
      Toast.toast(context, msg: msg);
      if (result == 1 && mounted) {
        // APPLIC.eventBus.fire(GetCardEven()); //发送通知
        Navigator.of(context).pop(account + ';' + name);
      }
    }
  }
}
